﻿using System;
using System.IO; 
using System.Text; 
using System.Reflection; 
using Microsoft.AspNetCore.Http;
using System.Text.Json;
using Microsoft.AspNetCore.Http.Internal;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using System.Runtime.CompilerServices;
using System.Linq;

namespace System.Extensions
{
    public static class RequestExtensions
    { 

        #region GET请求获得对象[HttpGet]
        /// <summary>
        /// GET请求获取参数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T QueryModel<T>(this HttpRequest request)
            where T : class, new()
        {
            T t = new T();
            Type type = t.GetType();

            try
            {
                foreach (PropertyInfo property in type.GetProperties())
                {
                    if (request.Query[property.Name].Count > 0)
                    {
                        property.SetValue(t, Convert.ChangeType((object)request.Query[property.Name][0], ConversionType.InitConversionType(property)), null);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return t;
        }
        #endregion


        #region HttpPost
        #region Form请求获得对象[HttpPost]
        /// <summary>
        ///  Form请求获得对象
        ///  每种类型必须是常用类型
        /// </summary>
        /// <param name="request"></param>
        /// <returns> </returns>
        public static T FormModel<T>(this HttpRequest request)
            where T : class, new()
        {
            T t = new T();
            Type type = t.GetType();

            try
            {
                foreach (PropertyInfo property in type.GetProperties())
                {
                    if (request.Form[property.Name].Count > 0)
                    {
                        if (!string.IsNullOrEmpty(request.Form[property.Name][0]))
                        {
                            property.SetValue(t, Convert.ChangeType((object)request.Form[property.Name][0], ConversionType.InitConversionType(property)), null);
                        } 
                    }
                }
            }
            catch (Exception)
            {
                t = default;
            }
            return t;
        }
        #endregion

        #region Body请求获得字符串[HttpPost]
        /// <summary>
        /// GetBody
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public static string Bodys(this HttpRequest Request)
        {
            string result = string.Empty;
            try
            {
                Request.EnableBuffering();
                using (Stream stream = Request.Body)
                {
                    byte[] buffer = new byte[Request.ContentLength.Value];
                    stream.Read(buffer, 0, buffer.Length);
                    result = Encoding.UTF8.GetString(buffer);
                    Request.Body.Position = 0;
                }
            }
            catch (Exception) { }
            return result;
        }
        #endregion

        #region Body异步请求获得字符串[HttpPost]
        /// <summary>
        /// Body异步请求获得字符串[HttpPost]
        /// </summary>
        /// <param name="Request"></param>
        /// <returns></returns>
        public static async Task<string> GetBodyAsync(this HttpRequest Request)
        {
            string result = string.Empty;
            try
            {
                Request.EnableBuffering();
                using (var reader = new StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
                {
                    result = await reader.ReadToEndAsync();
                    Request.Body.Position = 0;//以后可以重复读取
                }
            }
            catch (Exception) { }
            return result;
        }
        #endregion


        #region Body请求获得对象[HttpPost]
        /// <summary>
        /// Body请求获得对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Request"></param>
        /// <returns></returns>
        public static T BodyModel<T>(this HttpRequest Request)
            where T : new()
        {
            T t = new T();

            try
            {
                Request.EnableBuffering();
                using (Stream stream = Request.Body)
                {
                    byte[] buffer = new byte[Request.ContentLength.Value];
                    stream.Read(buffer, 0, buffer.Length);
                    string content = Encoding.UTF8.GetString(buffer);
                    Request.Body.Position = 0;
                    t = JsonSerializer.Deserialize<T>(content, JsonOpt.UnicodeRangesAll);
                }
            }
            catch (Exception)
            {
                t = default;
            }
            return t;
        }
        #endregion

        #region Body异步请求获得对象[HttpPost]
        /// <summary>
        /// Body异步请求获得对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Request"></param>
        /// <returns></returns>
        public static async Task<T> BodyModelAsync<T>(this HttpRequest Request)
            where T : new()
        {
            T t = new T();

            try
            {
                Request.EnableBuffering();
                using (var reader = new StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
                {
                    string body = await reader.ReadToEndAsync();
                    Request.Body.Position = 0;//以后可以重复读取
                    t = JsonSerializer.Deserialize<T>(body, JsonOpt.UnicodeRangesAll);
                }
            }
            catch (Exception e)
            { 
                throw e;
            }
            return t;
        }
        #endregion
        #endregion


        #region 获取请求参数[对象]
        /// <summary>
        /// 适用于HttpGet/HttpPost请求
        /// 对于其他请求后期待完善
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request"></param>
        /// <returns></returns>
        public static T Model<T>(this HttpRequest request)
            where T : class, new()
        {
            T t = new T();
            try
            {
                if (request.Method.ToUpper().Equals("GET")) t = request.QueryModel<T>();
                else if (request.HasFormContentType) t = request.FormModel<T>();
                else t = request.BodyModelAsync<T>().GetAwaiter().GetResult();
            }
            catch (Exception e)
            { 
                throw e;
            }
            return t;
        }

        #endregion


        #region 多次获取Body内容
        /// <summary>
        /// 多次获取Body内容 
        /// 主要用于2.0时代 3.0时代弃用
        /// Request.EnableRewind();//2.0时代
        /// Request.EnableBuffering();//3.0时代
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Request"></param>
        /// <returns></returns>
        public static T BodyModels<T>(this HttpRequest Request) where T : new()
        {
            T t = new T();
            try
            {
                Request.EnableBuffering();
                using (var stream = new MemoryStream())
                {
                    Request.Body.Position = 0;
                    Request.Body.CopyTo(stream);
                    string body = Encoding.UTF8.GetString(stream.ToArray());
                    t = JsonSerializer.Deserialize<T>(body, JsonOpt.UnicodeRangesAll);
                }
            }
            catch (Exception)
            {
                t = default;
            }
            return t;
        }
        #endregion

        #region 获取请求数据
        /// <summary>
        /// 获取请求数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static string Params(this HttpRequest request)
        {
            string result = string.Empty;
            try
            {
                if (request.Method.ToUpper().Equals("GET")) result = request.Query.Select(v => new { v.Key, v.Value }).ToJson();
                else if (request.HasFormContentType) result = request.Form.Select(v => new { v.Key, v.Value }).ToJson();
                else if (request.Method.ToUpper().Equals("DELETE")) result = string.Empty;
                else if (request.Method.ToUpper().Equals("PUT")) result = string.Empty;
                else result = request.Bodys();
            }
            catch (Exception e)
            {
                throw e;
            }
            return result;
        }
        #endregion
         

        #region 获得客户端真实IP地址
        /// <summary>
        /// 获得客户端真实IP地址
        /// </summary>
        /// <param name="request"></param>
        /// <returns>IP地址</returns>
        public static string GetUserRealIp(this HttpRequest request)
        {
            string proxyIps = request.Headers["X-Forwarded-For"];
            if (!string.IsNullOrWhiteSpace(proxyIps))
                return proxyIps.Split(',')[0].Trim();

            //return request.UserHostAddress;
            string ip = string.Empty;
            if (request != null)
            {
                ip = request.Headers["X-Real-IP"].ToString();
                if (request.Headers.ContainsKey("X-Real-IP") && !string.IsNullOrEmpty(ip))
                {
                    return ip;
                }

                ip = request.Headers["X-Forwarded-For"].ToString();
                if (request.Headers.ContainsKey("X-Forwarded-For") && !string.IsNullOrEmpty(ip))
                {
                    return ip;
                }
            }

            if (request.HttpContext.Connection != null)
            {
                if (request.HttpContext.Connection.RemoteIpAddress != null)
                {
                    ip = request.HttpContext.Connection.RemoteIpAddress.ToString();
                }
            }
            if (!ip.IsEmpty()) ip = ip.Substring(ip.LastIndexOf(':') + 1);
            return ip;
        }
        #endregion

    }
}
